package com.pxx.service.controller;

import com.item.common.PageResult;
import com.pxx.item.pojo.Sku;
import com.pxx.item.pojo.TbSpuDetail;
import com.pxx.item.pojo.vo.SpuVo;
import com.pxx.service.service.GoodsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GoodsController {


    @Autowired
    GoodsService goodsService;

    /**
     * 查询商品
     * page:当前页
     * rows：每页大小
     * key:过滤条件
     * saleable:上架或者下架
     * @return
     */
    @GetMapping("/spu/page")
    public ResponseEntity<PageResult<SpuVo>> querySpuVoPage(
         @RequestParam(value = "key",required = false) String key,
         @RequestParam(value = "saleable",required = false)   Boolean saleable,
         @RequestParam(value = "page",defaultValue = "1")    Integer page,
         @RequestParam(value = "rows",defaultValue = "5")     Integer rows
    ){

        PageResult<SpuVo> pageList =   goodsService.querySpuVoPage(key,saleable,page,rows);
        if (CollectionUtils.isEmpty(pageList.getItems())){
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(pageList);
    }


    @PostMapping("/goods")
    public ResponseEntity<Void> saveGoods(@RequestBody SpuVo spuVo){
        goodsService.saveGoods(spuVo);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    @PutMapping("/goods")
    public ResponseEntity<Void> updateGoods(@RequestBody SpuVo spuVo){
        goodsService.updateGoods(spuVo);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    /**
     * 根据spuId查询spuDetail的详情
     * @param spuId
     * @return
     */
    @GetMapping("/spu/detail/{spuId}")
    public ResponseEntity<TbSpuDetail> querySpuDetailBySpuId(@PathVariable("spuId")Long spuId){
       TbSpuDetail spuDetail =  goodsService.querySpuDetailBySpuId(spuId);
        return ResponseEntity.ok(spuDetail);
    }


    /**
     * 通过spuId查询skus的列表数据
     */
    @GetMapping("/sku/list")
    public ResponseEntity<List<Sku>> querySkuListBySpuId(@RequestParam("id")Long id){
        List<Sku> list =   goodsService.querySkuListBySpuId(id);
        if (CollectionUtils.isEmpty(list)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(list);
    }

}
